package com.qfedu.edu.orderservice.slot.impl;

import com.qfedu.edu.exception.BusinessException;
import com.qfedu.edu.orderservice.slot.base.SlotChain;
import com.qfedu.edu.orderservice.slot.generic.GenericSlot;
import com.qfedu.edu.result.ResponseCode;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

/**
 * @author xiaobobo
 * @title: SlotChainImpl
 * @projectName seckill-fy-2401-parent
 * @description: 这个就是Slot的实现类
 * @date 2024/11/11  16:41
 */
@Component
public class SlotChainImpl implements SlotChain {

    @Autowired
    private List<GenericSlot> genericSlots;

    //这个里面放的是咋们的这个slot实例
    private TreeSet<GenericSlot> treeSets=new TreeSet<>();

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public void dealRequest(HttpServletRequest req, HttpServletResponse resp) {
        //这里来写就一定有数据
        for (int i = 0; i <genericSlots.size() ; i++) {
             treeSets.add(genericSlots.get(i));
        }

        RLock rLock = redissonClient.getLock("锁");
        try{
            //下面就开始加锁
            if (rLock.tryLock()) {
                //TODO 这个代码一定要加分布式锁...
                //在这里我们需要启动这个实例
                Iterator<GenericSlot> iterator = treeSets.iterator();
                while (iterator.hasNext()) {
                    GenericSlot next = iterator.next();
                    next.dealRequest(req, resp);
                }
            }
        }catch (Exception err){
             throw new BusinessException(ResponseCode.LOCK_EXCEPTION);
        }finally {
            //执行到这里需要释放这个锁...
            rLock.unlock();
        }
    }
}
